<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区 -->
    <el-card>
      <el-alert
        title="注意：只允许为第三级分类设置相关参数"
        type="warning"
        :closable="false"
        show-icon
      >
      </el-alert>
      <!-- 选择商品分类区域 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类：</span>
          <!-- 选择商品分类的级联选择框 -->
          <el-cascader
            expandTrigger="hover"
            v-model="selectedCateKeys"
            :options="cateList"
            :props="cateProps"
            @change="handleChange"
            clearable
          ></el-cascader>
        </el-col>
        <el-col></el-col>
      </el-row>

      <!-- tab 页签区 -->
      <el-tabs v-model="activeName" @tab-click="handleChange">
        <!-- 添加动态参数的面板----------------------------------- -->
        <el-tab-pane label="动态参数" name="many">
          <!-- 添加参数按钮 -->
          <el-button
            type="primary"
            size="mini"
            @click="showManyDialog"
            :disabled="isBtnDisabled"
            >添加参数</el-button
          >
          <!-- 循环渲染Tag标签 -->

          <!-- 动态数据表格 -->
          <el-table :data="manyData" border stripe>
            <!-- 扩展列 动态-->
            <el-table-column type="expand">
              <template slot-scope="data">
                <el-tag
                  :key="ind"
                  v-for="(item, ind) in data.row.attr_vals"
                  closable
                  @close="delTag(ind, data.row)"
                >
                  {{ item }}
                </el-tag>
                <!-- 输入的文本框  -->
                <el-input
                  class="input-new-tag"
                  v-if="data.row.inputVisible"
                  v-model="data.row.addTaginputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="addTag(data.row)"
                  @blur="addTag(data.row)"
                >
                </el-input>
                <!-- 新增的按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(data.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="editCateParams(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="deleteParams(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 添加静态参数的面板------------------------------------- -->
        <el-tab-pane label="静态属性" name="only">
          <!-- 添加属性的按钮 -->
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="showManyDialog"
            >添加属性</el-button
          >
          <!-- 静态数据表格 ------------------------------------->
          <el-table :data="onlyData" border stripe>
            
             <!-- 扩展列 静态 -->
            <el-table-column type="expand">
              <template slot-scope="data">
                <el-tag
                  :key="ind"
                  v-for="(item, ind) in data.row.attr_vals"
                  closable
                  @close="delTag(ind, data.row)"
                >
                  {{ item }}
                </el-tag>
                <!-- 输入的文本框  -->
                <el-input
                  class="input-new-tag"
                  v-if="data.row.inputVisible"
                  v-model="data.row.addTaginputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="addTag(data.row)"
                  @blur="addTag(data.row)"
                >
                </el-input>
                <!-- 新增的按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(data.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name">
            </el-table-column>

            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="editCateParams(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="deleteParams(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加分类动态属性对话框-------------------------- -->
    <el-dialog
      :title="activeName == 'many' ? '添加动态属性' : '添加静态参数'"
      :visible.sync="isShowManyDialog"
      width="50%"
    >
      <!-- 内容区 -->
      <el-form :model="addManyForm" label-width="80px" :rules="addManyFormRule">
        <el-form-item
          :label="activeName == 'many' ? '添加动态属性' : '添加静态参数'"
        >
          <el-input v-model="addManyForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <!-- 按钮区 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="isShowManyDialog = false">取消</el-button>
        <el-button type="primary" @click="doAddMany">确定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑------------------------------------- -->
    <el-dialog
      :title="activeName == 'many' ? '修改动态属性' : '修改静态参数'"
      :visible.sync="editDdialogVisible"
      width="50%"
    >
      <!-- 内容区 -->
      <el-form :model="eaitManyForm" label-width="80px">
        <el-form-item label="编辑参数">
          <el-input v-model="eaitManyForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <!-- 按钮区 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCateParamsSubmit"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>


<script>
export default {
  data() {
    return {
      //分类下拉框数据数组
      cateList: [],
      //用户在级联下拉菜单中选中的分类id
      selectedCateKeys: [],
      //这是被激活的页签名称
      activeName: 'many',
      manyData: [], //动态属性数组
      onlyData: [], //静态属性数值
      isShowManyDialog: false,
      editDdialogVisible: false,
      //添加动态参数的数据对象
      addManyForm: {
        attr_name: '', //参数名字
        attr_sel: 0, //参数类型 (many-only)
      },
      //添加动态参数检验规则对象
      addManyFormRule: {
        attr_name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
        ],
      },
      eaitManyForm: {
        attr_name: '', //参数名字
      },
      attrId: 0,

      //配置级联菜单中数据如何展示
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
      },
      //控制按钮与文本框的显示
      // inputVisible: false,
      // //文本框输入的内容
      // inputValue: '',
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    async addTag(rowData) {
      //数据检查
      //隐藏文本框
      //将新增的tag放在视图中
      //将指南针的tag提交到服务器接口
      //数据检查 如果为输入  清空本部框 并隐藏
      if (rowData.addTaginputValue.trim().length === 0) {
        rowData.addTaginputValue = ''
        rowData.inputVisible = false
        return
      }
      //隐藏文本框 显示新增的tag按钮
      rowData.attr_vals.push(rowData.addTaginputValue.trim())
      rowData.addTaginputValue = ''

      //将新增tag提交服务器接口保存
      this.saveAttrVals(rowData)
      //隐藏文本框
      rowData.inputVisible = false
    },
    async getCateList() {
      //获取所有的商品分类列表
      const { data: res } = await this.$http.get('categories')

      if (res.meta.status !== 200) {
        return this.$message.error('获取分类数据失败')
      }
      //将数据列表赋值给cateList
      this.cateList = res.data
    },// 保存 对 attr_vals 的 修改---------------------------------------
    async saveAttrVals(row) {
      const { data: resData } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: this.activeName,
        attr_vals: row.attr_vals.join(' '),
      })
      if (resData.meta.status !== 200) {
        return this.$message.error(resData.meta.msg)
      }
      this.$message.success(resData.meta.msg)
    },


    //级联选择框选中项变化 会触发这个函数
    async handleChange() {
      //如果选中类别id数组 元素少于3个
      //说明没有选中第三级分类 所有清空选中项
      if (this.selectedCateKeys.length < 3) {
        //清空下拉框绑定的数据项数组 从而达到清空下拉框选中项的目的
        this.selectedCateKeys.length = 0
        //清空动态数据项和静态数据项 表格 数组
        this.manyData = []
        this.onlyData = []
        //停止代码执行
        return
      }
      let { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: this.activeName },
        }
      )

      //修改返回数据项数组中 attr_vals 属性 将它改为数组
      res.data.forEach((ele) => {
        // ele.attr_vals = ele.attr_vals ? ele.attr_vals.split(',') : []

        //如果不为空 则拆分为新数组中元素attr_vals属性 将它改为数组
        if (ele.attr_vals) ele.attr_vals = ele.attr_vals.split(',')
        else ele.attr_vals = []
        //为每一个数据对象添加一个
        //控制文本框的显示与隐藏inputVisible属性 来控制当前行的 添加标签和文本框

        ele.inputVisible = false
        //为每一个数据对象 添加addTaginputValue 属性 来保存输入的新文本
        ele.addTaginputValue = ''
      })
      console.log('handleChange', res)

      //如果失败
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      //如果成功  根据当前选项卡名字  将数据设置给不同数组
      if (this.activeName == 'many') this.manyData = res.data
      else if (this.activeName == 'only') this.onlyData = res.data
    },

    //显示添加动态参数 对话框
    async showManyDialog() {
      this.isShowManyDialog = true
    },

    //确定新增动态参数-----------------------------------
    async doAddMany() {
      ///获取选中tab栏的name值(many-only)
      this.addManyForm.attr_sel = this.activeName
      //异步请求接口 获取数据后解构 data属性 到res
      const { data: res } = await this.$http.post(
        `categories/${this.cateId}/attributes`,
        this.addManyForm
      )
      //如果失败 报错
      if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
      //如果成功 关闭对话框  重置对话框
      this.isShowManyDialog = false
      this.addManyForm.attr_name = ''
      this.addManyForm.attr_sel = 'many'
      //刷新 分类 的动态或静态数据列表
      this.handleChange()
    },

    // 显示编辑对话框
    editCateParams(rowData) {
      //将当前修改数据项的id保存
      this.attrId = rowData.attr_id
      //将当前数据项目名称 显示到文本框
      this.eaitManyForm.attr_name = rowData.attr_name
      //显示修改对话框
      this.editDdialogVisible = true
    },

    // 提交编辑参数
    async editCateParamsSubmit() {
      console.log(this.eaitManyForm)
      //   类型
      //获取数据类型 根据 tab选项卡
      this.eaitManyForm.attr_sel = this.activeName
      let { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${this.attrId}`,
        this.eaitManyForm
      )
      if (res.meta.status != 200) return this.$message.error('更新失败')
      this.$message.success('修改成功')
      this.editDdialogVisible = false
      this.handleChange()
    },

    // 删除分类 数据项(动态/静态)
    async deleteParams(rowData) {
      let { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${rowData.attr_id}`
      )

      this.$message.success(res.meta.msg)
      this.handleChange()
    },

    //显示添加数据项 标签 文本框的方法
    //点击按钮 输入文本框
    showInput(row) {
      //将数据当前行数据对象 里的 开关打开 显示新增文本框
      row.inputVisible = true
      //添加数据项标签的属性
      // row.addTaginputValue = ''
      row.addTaginputValue = ''
      //将显示的文本框设置焦点

      // nextTick 作用 当页面上元素被重新渲染后才会调用这个方法
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    async updateTag(rowData) {
      const { data: resData } = await this.$http.put(
        `categories/${this.cateId}/attributes/${rowData.attr_id}`,
        {
          attr_name: rowData.attr_name,
          attr_sel: rowData.attr_sel,
          //要将tab数据存入 数据库之前 先转成 分割的字符串
          attr_vals: rowData.attr_vals.join(','),//[1,2,3] -> "1,2,3"
        }
      )
      if (resData.meta.status !== 200)
        return this.$message.error(resData.message.msg)
      this.$message.success(resData.meta.msg)
    },

    //删除tag事件
    delTag(ind, rowData) {
      this.$MessageBox.confirm('确定删除吗?', '标题名称', {
        confirmButtonText: '确定',
        callback: (action) => {
          if (action == 'cancel') return
          rowData.attr_vals.splice(ind, 1)
          this.updateTag(rowData)
        },
      })
    },
  },
  computed: {
    //如果按钮需要被禁用 则返回true 否则返回false
    isBtnDisabled() {
      if (this.selectedCateKeys.length !== 3) {
        return true
      }
      return false
    },
    //当前 选中的三级分类的id
    cateId() {
      if (this.selectedCateKeys.length === 3) {
        return this.selectedCateKeys[2]
      }
      return null
    },
  },
}
</script>

<style lang="less" scoped>
.cat_opt {
  margin: 15px 0;
}
.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 100px;
}
</style>

 